﻿using System;
using System.Configuration;
using System.Net.Mail;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using AzureQueue;

namespace WebPages.Account
{
    public partial class ResetPassword : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// TODO: Lots of calls to GetUser(), look at a way to only do this once by using viewstate or something
        /// </summary>
        /// <returns></returns>
        MembershipUser GetUser()
        {
            var userNameOrEmail = UserNameOrEmail.Text;
            var user = Membership.GetUser(userNameOrEmail, false);
            if (user == null)
            {
                userNameOrEmail = Membership.GetUserNameByEmail(userNameOrEmail);
                user = Membership.GetUser(userNameOrEmail, false);
            }
            return user;
        }

        protected void ValidateUserNameOrEmail(object source, ServerValidateEventArgs args)
        {
            try
            {
                args.IsValid = (GetUser() != null);
            }
            catch (Exception)
            {
                args.IsValid = false;
            }
        }

        void SendConfirmationEmail(string userName, string newPassword, string emailAddress)
        {
            // Now lets create an email message
            var emailMessage = new StringBuilder();
            var header = Resources.Email.EmailHeader.Replace("{0}", "Your new MyApp account password");
            emailMessage.Append(header);
            emailMessage.Append(string.Format("Hello, {0}.<br />Your new password is: <span class=\"password\">{1}</span>", userName, newPassword));
            var footer = String.Format(Resources.Email.EmailFooter, "This e-mail was sent because someone reset a password to an account at <a href=\"http://www.MyApp.com\">www.MyApp.com</a> that is registered to your e-mail address.");
            emailMessage.Append(footer);
            var fromEmail = ConfigurationManager.AppSettings["fromEmail"];

            // Send the email
            var queueDataSource = new AzureQueueDataSource();
            queueDataSource.SendEmail(fromEmail, emailAddress, "Your MyApp account password has been reset", emailMessage.ToString());
        }

        protected void ValidateAnswer(object source, ServerValidateEventArgs args)
        {
            try
            {
                var user = GetUser();
                var newPassword = user.ResetPassword(PasswordAnswer.Text);
                var isValid = !String.IsNullOrEmpty(newPassword);
                if (isValid) SendConfirmationEmail(user.UserName, newPassword, user.Email);
                args.IsValid = isValid;
            }
            catch (Exception)
            {
                args.IsValid = false;
            }
        }

        bool AssertValidationGroup(string name)
        {
            var validators = Page.GetValidators(name);
            foreach (IValidator validator in validators)
            {
                validator.Validate();
                if (!validator.IsValid) return false;
            }
            return true;
        }

        protected void OnNextButtonClick(object sender, WizardNavigationEventArgs e)
        {
            switch (ResetPasswordWizard.ActiveStep.Title)
            {
                case "Identify User":
                    e.Cancel = !AssertValidationGroup("ResetPasswordValidationGroup1");
                    if (!e.Cancel) PasswordQuestion.Text = GetUser().PasswordQuestion;
                    break;
                case "Answer Question":
                    e.Cancel = !AssertValidationGroup("ResetPasswordValidationGroup2");
                    break;
            }
        }

    }
}